<?php
/**
 * Created by PhpStorm.
 * User: 小灰灰
 * Date: 2023-10-15
 * Time: 9:55:30
 * Info:
 */

namespace plugin\slide\app\controller;

use support\Request;
use plugin\slide\app\model\SlideCate as SlideCateModel;
use plugin\slide\app\model\Slide as SlideModel;

class SlideCateController
{

    /**
     * 分类列表
     */
    public function index(Request $request)
    {
        if ($request->isAjax()) {
            $data = SlideCateModel::select()->toArray();

            return json(['code' => 0, 'data' => $data, 'msg' => 'ok']);
        }

        return view('admin/slide_cate/index');
    }

    public function add(Request $request)
    {
        if ($request->isPost()) {
            $param = $request->post();
            if (empty($param['title'])) {
                return json(['code' => 0, 'msg' => '分组名称不能为空']);
            }
            if (empty($param['name'])) {
                return json(['code' => 0, 'msg' => '标识不能为空']);
            }
            SlideCateModel::create($param);

            return json(['code' => 200, 'msg' => '操作成功']);
        }

        return view('admin/slide_cate/add');
    }

    public function edit(Request $request)
    {
        if ($request->isPost()) {
            $param = $request->post();
            if (empty($param['id'])) {
                return json(['code' => 0, 'msg' => '参数错误']);
            }
            if (empty($param['title'])) {
                return json(['code' => 0, 'msg' => '分组名称不能为空']);
            }
            if (empty($param['name'])) {
                return json(['code' => 0, 'msg' => '标识不能为空']);
            }
            SlideCateModel::update($param, ['id' => $param['id']]);

            return json(['code' => 200, 'msg' => '操作成功']);
        }
        $id = $request->get('id');
        if (empty($id)) {
            return json(['code' => 0, 'msg' => '参数错误']);
        }
        $data = SlideCateModel::find($id);
        if (empty($data)) {
            return json(['code' => 0, 'msg' => '获取数据失败']);
        }

        return view('admin/slide_cate/edit', ['data' => $data]);
    }

    public function delete(Request $request)
    {
        $id = $request->get('id');
        if (empty($id)) {
            return json(['code' => 0, 'msg' => '参数错误']);
        }
        //判断分类下是否存在数据，如果有禁止删除
        $slideCount = SlideModel::where('slide_id', $id)->count();
        if ($slideCount) {
            return json(['code' => 0, 'msg' => '请先删除分类下数据']);
        }
        SlideCateModel::where('id', $id)->delete();

        return json(['code' => 200, 'msg' => '删除成功']);
    }

}